package com.example.yam.greenapp;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class DisplayActivity extends AppCompatActivity {
    //常量
    private String TAG = "DisplayActivity";
    //变量
    private String totalPrice = null;
    private String dnum = null;
    //控件
    private ListView listView = null;
    private TextView shdzMessage = null;//收获地址信息
    private TextView total = null;//总价
    private Button pay = null;//付款按钮

    //适配器
    DGoodsAdapter dGoodsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);

        this.listView = (ListView) super.findViewById(R.id.display_shoplist);
        this.shdzMessage = (TextView) super.findViewById(R.id.display_receiverMessage);
        this.total = (TextView) super.findViewById(R.id.display_total);
        this.pay = (Button) super.findViewById(R.id.display_pay);

        this.pay.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent it = new Intent(DisplayActivity.this,PayFinishActivity.class);
                it.putExtra("totalprice",DisplayActivity.this.totalPrice);
                it.putExtra("dnum",DisplayActivity.this.dnum);
                startActivity(it);

                DisplayActivity.this.finish();
            }
        });
        setMessage();
        //工具栏--返回
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    //设置数据
    public void setMessage(){
        this.dGoodsAdapter = new DGoodsAdapter(DisplayActivity.this,R.layout.dgoodslist,MyApplication.dialoggoodsList);
        this.listView.setAdapter(this.dGoodsAdapter);
        this.shdzMessage.setText(MyApplication.myshdz.getPhone()+"("+MyApplication.myshdz.getName()+")"+MyApplication.myshdz.getLocation());
        this.total.setText(String.valueOf(MyApplication.diaSum)+"元");
        DoDingdanTask doDingdanTask = new DoDingdanTask();
        doDingdanTask.execute();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //加入购物车--写入服务器--使用post
    public class DoDingdanTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            String path = MyApplication.localhost + "Green/index.php/indexg/Nopay";
            URL url = null;
            HttpURLConnection httpConnection = null;

            String res=null;
            //System.out.println("异步操作开始");
            try {
                //post传值
                url = new URL(path);
                Log.d(TAG, path);
                httpConnection = (HttpURLConnection) url.openConnection();
                httpConnection.setRequestMethod("POST");
                DataOutputStream out = new DataOutputStream(httpConnection.getOutputStream());
                Log.v(TAG,MyApplication.changeDiagoodListToJSONArrayString());
                Log.v(TAG,MyApplication.changeReceiverMessageToJSONObjectString());
                Log.v(TAG,MyApplication.user.getJsonObject());

                out.writeBytes("goods="+MyApplication.changeDiagoodListToJSONArrayString()+"&shdz="
                        + MyApplication.changeReceiverMessageToJSONObjectString()+"&user="+MyApplication.user.getJsonObject());

                httpConnection.setConnectTimeout(8000);
                httpConnection.setReadTimeout(8000);

                if (httpConnection.getResponseCode() == 200) {
                    Log.d(TAG,"网络连接成功");

                    InputStream in = httpConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();

                    String line;
                    while((line = reader.readLine())!=null){
                        response.append(line);
                    }
                    res=response.toString();
                    Log.v(TAG,"我是结果"+res);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // TODO: register the new account here.
            return res;
        }
        @Override
        protected void onPostExecute(String success) {
            if(!TextUtils.isEmpty(success)) {//链接成功
                parseJSONobject(success);
                Log.v(TAG,success);
            } else {
                Toast.makeText(DisplayActivity.this,"未连接到服务器，请稍后重试！！",Toast.LENGTH_LONG).show();
            }
        }
    }
    //json解析
    private void parseJSONobject(String ss){
        try{
            JSONObject jsb = (JSONObject) new JSONObject(ss);
            this.totalPrice = jsb.getString("totalprice");
            this.dnum = jsb.getString("dnum");
            Log.v(TAG,"我需要的信息--总价和订单号是"+this.totalPrice+"|"+this.dnum);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
